window.addEventListener('load', () => {
    // 获取搜索input
    var searchBox = document.getElementById('searchBox');
    var listBox = document.getElementById('listBox');
    var searchTimer = null;
    // 上一次搜索返回的结果长度
    var formerLength = 0;
    searchBox.addEventListener('input', function () {
        clearTimeout(searchTimer);
        var key = null;
        key = this.value;
        if (key !== '') {
            // 发送请求
            const url = 'http://47.113.197.172:80/articles/search';

            // 防抖优化
            searchTimer = setTimeout(function () {
                axios.get(url, {
                    // 请求头携带的数据
                    params: {
                        keyword: key,
                        offset: 0,
                        limit: 5
                    },
                })
                    .then(Response => {
                        appendSearchResult(Response);
                    })
                    .catch(err => {
                        console.log(err);
                    })
            }, 800);

        }
        else {
            listBox.style.display = 'none';
        }

        function appendSearchResult(Response) {
            var titleArrLength = Response.data.data.articlesList.length;
            var listBoxFormerLi = listBox.querySelectorAll('li');
            for (i = 0; i < formerLength; i++) {
                listBox.removeChild(listBoxFormerLi[i]);
                // console.log(listBoxFormerLi[i].innerHTML);
            }

            for (i = 0; i < (titleArrLength < 5 ? titleArrLength : 5); i++) {
                var listBoxLi = document.createElement('li');
                listBoxLi.innerHTML = Response.data.data.articlesList[i].title;
                // 获取每个文章的id并作为属性保存，方便后面确定是哪一篇文章
                listBoxLi.id = Response.data.data.articlesList[i].id;
                listBox.appendChild(listBoxLi);
                // console.log(listBoxLi.id);
            }

            listBox.style.display = 'block';
            // 获取本次返回结果的长度，用于下一次搜索时删除已生成的结果
            formerLength = titleArrLength;

            var listBoxLi = listBox.querySelectorAll('li');

            for (i = 0; i < listBoxLi.length; i++) {
                listBoxLi[i].addEventListener('click', function () {
                    // 能够成功获取到每篇文章的id
                    // console.log(this.id);
                    var baseUrl = 'http://47.113.197.172:80/articles/';
                    var id = this.id;
                    var finalUrl = baseUrl + id;
                    // 成功获取请求的文章接口
                    // console.log(finalUrl);
                    // 将需要调用的接口存到本地，在打开文章详情页可以跨页面调用
                    sessionStorage.setItem('finalUrl', finalUrl);
                    // 跳转到文章详情页
                    window.open("../html/passage.html");
                })
            }
        }
    })

    var searchContainer = document.querySelector('.searchContainer');
    var searchIcon = document.querySelector('.searchIcon');
    var searchIconImg = searchIcon.getElementsByTagName('div');
    var createCenter = document.querySelector('.createCenter');

    searchBox.addEventListener('focus', function () {
        searchBox.placeholder = '搜索文章/小册/标签/用户';
        searchContainer.style.border = '1px solid rgb(30, 128, 255)';
        searchIcon.style.backgroundColor = 'rgb(234, 242, 255)';
        searchIconImg[0].style.color = 'rgb(43, 135, 255)';
        createCenter.style.display = 'none';
        listBox.style.width = searchContainer.offsetWidth - 2 + 'px';
        listBox.style.display = 'block';
        // 如果搜索栏里面没有内容，隐藏列表
        if (searchBox.value == '') {
            listBox.style.display = 'none';
        }
    })

    searchBox.addEventListener('blur', function () {
        searchBox.placeholder = '探索稀土掘金';
        searchContainer.style.border = '1px solid rgb(194, 200, 209)';
        searchIcon.style.backgroundColor = 'rgb(242, 243, 245)';
        searchIconImg[0].style.color = 'rgb(166, 167, 169)';
        createCenter.style.display = 'block';
        listBox.style.width = searchContainer.offsetWidth - 2 + 'px';
        // listBox.style.display = 'none';
    })

    var headerTitle = document.querySelector('.headerTitle');
    var turnIndex = headerTitle.querySelector('li');
    turnIndex.onclick = function () {
        window.location.href = '../html/index.html';
    }



    // 登录与注册界面

    // 打开关闭界面
    var userOut = document.querySelector('.userOut');
    var loginBlock = document.querySelector('.loginBlock');
    var closeBtn = document.querySelector('.close');

    userOut.onclick = function () {
        // 初始化并显示界面
        loginBlock.style.display = 'block';
    }
    closeBtn.onclick = function () {
        loginBlock.style.display = 'none';
    }

    // 切换登录与注册
    var loginFun = document.querySelector('.loginFun');
    var registerFun = document.querySelector('.registerFun');
    var login = document.querySelector('.login');
    var register = document.querySelector('.register');
    var go = document.querySelectorAll('.go');

    loginFun.onclick = function () {
        login.style.display = 'block';
        register.style.display = 'none';
        loginFun.style.top = '-87px';
        registerFun.style.top = '-20px';
        hidden.style.display = 'none';
        interface.style.backgroundColor = 'white';
    }
    registerFun.onclick = function () {
        register.style.display = 'block';
        login.style.display = 'none';
        registerFun.style.top = '-87px';
        loginFun.style.top = '-20px';
        hidden.style.display = 'none';
        interface.style.backgroundColor = 'white';
    }
    go[0].onclick = function () {
        register.style.display = 'block';
        login.style.display = 'none';
        registerFun.style.top = '-87px';
        loginFun.style.top = '-20px';
    }
    go[1].onclick = function () {
        login.style.display = 'block';
        register.style.display = 'none';
        loginFun.style.top = '-87px';
        registerFun.style.top = '-20px';
    }

    // 管理员注册页面
    var hidden = document.querySelector('#hidden');
    var hiddenDot = document.querySelector('.hiddenDot');
    var interface = document.querySelector('.interface');
    hiddenDot.onclick = function () {
        login.style.display = 'none';
        register.style.display = 'none';
        hidden.style.display = 'block';
        interface.style.backgroundColor = 'gray';
    }

    // 输入用户名和密码时改变顶部图片
    var userName = document.querySelectorAll('.userName');
    var userPassword = document.querySelectorAll('.userPassword');
    var inputState = document.querySelector('.inputState');

    userName[0].onfocus = function () {
        inputState.children[0].src = '../img/pleaseEnter.svg';
    }
    userPassword[0].onfocus = function () {
        inputState.children[0].src = '../img/closeEye.svg';
    }
    userName[1].onfocus = function () {
        inputState.children[0].src = '../img/pleaseEnter.svg';
    }
    userPassword[1].onfocus = function () {
        inputState.children[0].src = '../img/closeEye.svg';
    }
    userName[0].onblur = function () {
        inputState.children[0].src = '../img/openEye.svg';
    }
    userName[1].onblur = function () {
        inputState.children[0].src = '../img/openEye.svg';
    }
    userPassword[0].onblur = function () {
        inputState.children[0].src = '../img/openEye.svg';
    }
    userPassword[1].onblur = function () {
        inputState.children[0].src = '../img/openEye.svg';
    }

    // 免密码开关
    var freeBtn = document.getElementById('free');
    // 用户登录
    var loginBtn = document.getElementById('loginBtn');
    loginBtn.addEventListener('click', function () {
        var loginName = document.getElementById('loginName').value;
        var loginPassword = document.getElementById('loginPassword').value;
        // 是否记住密码
        if (freeBtn.checked == true) {
            localStorage.setItem('name', loginName);
            localStorage.setItem('password', loginPassword);
            // flag记录是否记住密码
            localStorage.setItem('remFlag', 1);
            // 获取当前时间戳（ms）
            var timestamp = Date.parse(new Date());
            localStorage.setItem('timestamp', timestamp);
        }
        axios.post('http://47.113.197.172:80/user/login', {
            name: loginName,
            password: loginPassword
        })
            .then(Response => {
                // console.log(Response.data);
                // 获取登录的用户身份和token令牌
                var token = Response.data.token;
                var id = Response.data.id;
                sessionStorage.setItem('flag', 1);
                sessionStorage.setItem('token', token);
                sessionStorage.setItem('id', id);
                sessionStorage.setItem('name', loginName);
                sessionStorage.setItem('password', loginPassword);

                loginSuccess();

            })
            .catch(err => {
                console.log(err);
                alertMes(message.children[1]);
            })
    })

    // 普通用户注册
    var registerBtn = document.getElementById('registerBtn');
    registerBtn.addEventListener('click', function () {
        var registerName = document.getElementById('registerName').value;
        var registerPassword = document.getElementById('registerPassword').value;
        // 5-12位账户名
        var tempName = /^\w{5,12}$/;
        // 8位以上含数字英文的密码
        // 不全含数字、不全含英文、由数字英文组成8位以上
        var tempPass = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,}$/;
        if (registerName != "" && registerPassword != ""
            && tempName.test(registerName) && tempPass.test(registerPassword)) {

            axios.post('http://47.113.197.172:80/user/register', {
                name: registerName,
                password: registerPassword,
                role: 0
            })
                .then(Response => {
                    console.log(Response);
                    alertMes(message.children[2]);
                })
                .catch(err => {
                    console.log(err);
                    alertMes(message.children[3]);
                })
        }
        else {
            alertMes(message.children[3]);
        }



    })

    // 管理员注册
    var registerBtn0 = document.getElementById('registerBtn0');
    registerBtn0.addEventListener('click', function () {
        var registerName0 = document.getElementById('registerName0').value;
        var registerPassword0 = document.getElementById('registerPassword0').value;
        // 5-12位账户名
        var tempName = /^\w{5,12}$/;
        // 8位以上含数字英文的密码
        // 不全含数字、不全含英文、由数字英文组成8位以上
        var tempPass = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,}$/;
        if (registerName0 != "" && registerPassword0 != ""
            && tempName.test(registerName0) && tempPass.test(registerPassword0)) {

            axios.post('http://47.113.197.172:80/user/register', {
                name: registerName0,
                password: registerPassword0,
                role: 1
            })
                .then(Response => {
                    console.log(Response);
                    alertMes(message.children[2]);
                })
                .catch(err => {
                    console.log(err);
                    alertMes(message.children[3]);
                })
        } else {
            alertMes(message.children[3]);
        }
    })

    // 消息提示
    var message = document.querySelector('.message');
    function alertMes(obj) {
        obj.style.animation = 'attention 2s ease-in-out';
        setTimeout(function () {
            obj.style.animation = null;
        }, 2000)
    }

    // 登录成功后显示登录状态的主页
    var loginSuccess = function () {
        alertMes(message.children[0]);
        setTimeout(function () {
            loginBlock.style.display = 'none';
            window.location.href = '../html/index.html';
        }, 2000);
    }

    // 登录成功后点击用户头像显示菜单列表
    var hiddenFun = document.querySelector('.hiddenFun');
    var userPhoto = document.querySelector('.userPhoto');
    var hiddenFunFlag = 0;
    userPhoto.onclick = function () {
        if (hiddenFunFlag === 0) {
            hiddenFun.style.display = 'block';
            hiddenFunFlag = 1;
        } else {
            hiddenFun.style.display = 'none';
            hiddenFunFlag = 0;
        }
    }

    // 部分页面跳转
    var goNotes = document.querySelector('.goNotes');
    var goUserMes = document.querySelector('.goUserMes');
    goNotes.onclick = function () {
        window.open("../html/articles.html");
    }
    goUserMes.onclick = function () {
        window.open("../html/userMes.html");
    }

    // 退出登录
    var exit = document.querySelector('.exit');
    exit.onclick = function () {
        var userOut = document.querySelector('.userOut');
        var userIn = document.querySelector('.userIn');
        // 显示用户退出后的界面
        userOut.style.display = 'block';
        userIn.style.display = 'none';
        // 清除本地缓存
        sessionStorage.removeItem('token');
        sessionStorage.removeItem('id');
        sessionStorage.removeItem('flag');
        sessionStorage.removeItem('name');
        sessionStorage.removeItem('password');
        // 如果记住密码登录后退出，清除本地缓存
        if (localStorage.getItem('timestamp')) {
            localStorage.removeItem('timestamp');
        }
        if (localStorage.getItem('name')) {
            localStorage.removeItem('name');
        }
        if (localStorage.getItem('password')) {
            localStorage.removeItem('password');
        }
        if (localStorage.getItem('remFlag')) {
            localStorage.removeItem('remFlag');
        }
        // 清空输入框内的值
        var input = document.querySelectorAll('input');
        for (i = 0; i < input.length; i++) {
            if (input[i].type !== 'button') {
                input[i].value = null;
            }
        }
        // 清空输入框内的值
        var textarea = document.querySelectorAll('textarea');
        for (i = 0; i < textarea.length; i++) {
            textarea[i].value = null;
        }
        // 返回主页
        window.location.href = '../html/index.html';
    }

    // 登录成功后动态获取用户头像
    var avatar = document.getElementById('avatar');
    var addAvatar = function () {
        var id = sessionStorage.getItem('id');
        var baseUrl = 'http://47.113.197.172:80/user/info/';
        var finalUrl = baseUrl + id;
        axios.get(finalUrl)
            .then(Response => {
                avatar.src = Response.data.data.avatar;
            })
            .catch(err => {
                console.log(err);
            })
    }

    // 判断用户登录状态并显示相应页面
    var state = function () {
        var flag = sessionStorage.getItem('flag');
        var userOut = document.querySelector('.userOut');
        var userIn = document.querySelector('.userIn');
        // 登录时的状态
        if (flag == 1) {
            console.log('已登录');
            userOut.style.display = 'none';
            userIn.style.display = 'flex';
            addAvatar();

        }
        // 未登录的状态
        else {
            console.log('未登录');
            userOut.style.display = 'block';
            userIn.style.display = 'none';
        }
    }
    state();

})